'use strict';
/**
 * @fileoverview 在线数据
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var moment = require('moment');
var _ = require('lodash');
var onlineMgr = require('../mgr/onlineMgr');
var dataApi = require('../libs/dataApi');
var onlineConf = require('../config/onlineConf');

var _initNextRewardId = function () {
    var online_conf = onlineConf.getFirstOnlineConf();
    return online_conf.id;
};

var _initNextRewardTime = function () {
    var online_conf = onlineConf.getFirstOnlineConf();
    return moment().unix() + online_conf.id;
};

/**
 * 在线数据
 */
var onlineSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 下次领取奖励的时间
    next_reward_time: {
        type: Number,
        default: _initNextRewardTime
    },

    // 下次领取在线奖励的id
    next_reward_id: {
        type: Number,
        default: _initNextRewardId
    }
});

onlineSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 下次领取在线奖励的id
 * @return {[type]} [description]
 */
onlineSchema.methods.getNextRewardId = function () {
    return this.next_reward_id;
};

/**
 * 设置下一次可以领取在线奖励的id
 * @return {[type]} [description]
 */
onlineSchema.methods.setNextRewardId = function (reward_id) {
    this.next_reward_id = reward_id;
};

/**
 * 设置下一次可以领取奖励的时间
 * @param {[type]} time [description]
 */
onlineSchema.methods.setNextRewardTime = function (time) {
    this.next_reward_time = time;
};

/**
 * 获取下次可以领奖的时间
 * @return {[type]} [description]
 */
onlineSchema.methods.getNextRewardTime = function () {
    return this.next_reward_time;
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
onlineSchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
onlineSchema.methods.push = function () {
    this.pushModify();
};

onlineSchema.methods.pushModify = function () {
    onlineMgr.sendOnlineChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send online message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!onlineSchema.options.toJSON) {
    onlineSchema.options.toJSON = {};
}
/* jshint unused:false */
onlineSchema.options.toJSON.transform = function (doc, ret) {
    delete ret.last_refresh_time;
    delete ret._id;
    delete ret.__v;
};

mongoose.model('Online', onlineSchema);
